/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 *
 *PmCloseApplyController
 * 项目闭环申请
 *
 * 修改纪录
 * 2020-05-23 版本：1.0 shenyouyi 创建。
 * @version 版本：1.0
 * @author 作者：shenyouyi
 * 创建日期：2020-05-23
 */

package com.topscomm.pm.controller;

import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboOrgService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pm.controller.auto.PmCloseApplyControllerAuto;
import com.topscomm.pm.pojo.PmCloseApplyEntity;
import com.topscomm.pm.pojo.PmProjectEntity;
import com.topscomm.pm.service.impl.PmCloseApplyService;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.DateUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;
import java.util.HashMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: shenyouyi
 * @date: 2020-05-23
 * @description:项目闭环申请Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/closeApply")
public class PmCloseApplyController extends PmCloseApplyControllerAuto implements IPmCloseApplyController {
	/**
	 * @author: shenyouyi
	 * @date: 2020-05-23
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" PmCloseApply.enabled=1 ");
		if (paraMap.containsKey("qry_projectid")) {
			String value = paraMap.get("qry_projectid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmCloseApply.projectid={0}", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmCloseApply.docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmCloseApply.docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmCloseApply.docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (PmCloseApply.deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (PmCloseApply.username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmCloseApply.deptcode like '{0}%'", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and PmCloseApply.state={0}", value);
		}
		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		sql .appendSingle(this.spellingSqlForProject(paraMap, "PmCloseApply","projectid","id"));

		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "", this.getUserBean());
			if (StringUtil.isEmpty(dataPession)) {
				sql.appendSingle(" and (" + MisStringUtil.createWhereByUsercodeFromProject(
						this.getUserBean().getUser(), "projectid",
						service.getDao().getTableName()) +
								" or PmCloseApply.usercode = '{0}')",
						this.getUserBean().getUser().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @author: shenyouyi
	 * @date: 2020-05-23
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 *
	 * @description: 提交审批前
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @author: shenyouyi
	 * @date: 2020-05-23
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交项目闭环申请申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"), DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
		List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmCloseApply", dataMap.get("deptcode").toString(),dataMap.get("usercode").toString(),null, "sortcode");
		Long flowid = flowidList.size()>0? ConvertUtil.convertToLong(flowidList.get(0).get("id")) :null;
		dataMap.put("flowid", flowid);
	}


	@Override
	@GetMapping({"/list"})
	public ResponseResult<Object> list(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSql(paraMap);
			paraMap.put("whereSql",sqlWhere);
			int totalCount = this.service.getCount(paraMap,"getPmCloseApplyAndProjectCount");
			List<Map<String, Object>> tempList = null;
			HashMap<String, Object> paraMap2 = new HashMap<>();
			paraMap2.put("curPageIndex",query.getCurrentPage());
			int beginCount=query.getCurrentPage()*query.getPageSize()-query.getPageSize();
			paraMap2.put("begincount",beginCount);
			paraMap2.put("pagesize", query.getPageSize());
			paraMap2.put("sidx", query.getSidx());
			paraMap2.put("sord", query.getSord());
			paraMap2.put("whereSql", sqlWhere);
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPage(paraMap2,"getPmCloseApplyAndProject");
			} else {
				tempList = this.service.queryMap(paraMap2,"queryMapByWhere1");
			}
			this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}

	@Transactional(rollbackFor = Exception.class)
	public void saveAndSubmitProjectCloseApply(PmProjectEntity project) throws Exception {
		try {
			Map<String, Object> closeApplyMap = new HashMap<>();
			FlowDatacodeCache flowDatacodeCache = (FlowDatacodeCache) SpringUtil.getBean("flowDatacodeCache");
			List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmCloseApply", project.getUsercode(), "sortcode");
			Date today = DateUtil.getZreoOfDay(new Date());
			closeApplyMap.put("projectid", project.getId());
			closeApplyMap.put("closedate", today);
			closeApplyMap.put("orgname", project.getOrgname());
			closeApplyMap.put("orgcode", project.getOrgcode());
			closeApplyMap.put("deptname", project.getOwnerdeptname());
			closeApplyMap.put("deptcode", project.getOwnerdeptcode());
			closeApplyMap.put("username", project.getUsername());
			closeApplyMap.put("usercode", project.getUsercode());
			closeApplyMap.put("docdate", today);
			closeApplyMap.put("flowid", flowidList.size() > 0 ? flowidList.get(0).get("id") : 0);
			closeApplyMap.put("submitdate", new Date());


			Class<PmCloseApplyEntity> entityClass = this.entityClass;
			PmCloseApplyEntity entity = entityClass.newInstance();
			entity.convertFromMap(closeApplyMap);
			PmCloseApplyEntity pmCloseApplyEntity = this.service.insert(entity);

			//  modify by wushenghong
			// 创建session 单据提交必须提供session  系统用户   modify by wushenghong
			PmCloseApplyService pmCloseApplyService = (PmCloseApplyService) SpringUtil.getBean("pmCloseApplyService");
			CboUserService cboUserService = (CboUserService) SpringUtil.getBean("cboUserService");
			CboDeptService cboDeptService = (CboDeptService) SpringUtil.getBean("cboDeptService");
			CboOrgService cboOrgService = (CboOrgService) SpringUtil.getBean("cboOrgService");
			List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(" code = 'QuartzUser' ");
			List<CboDeptEntity> cboDeptEntities = cboDeptService.queryByWhere(" code = 'D11803'");
			List<CboOrgEntity> cboOrgEntities = cboOrgService.queryByWhere(" code ='D1'");
			SessionUserBean sessionUserBean = new SessionUserBean();
			if (cboUserEntities.size() > 0 && cboDeptEntities.size() > 0 && cboOrgEntities.size() > 0) {
				sessionUserBean.setUser(cboUserEntities.get(0));
				sessionUserBean.setDept(cboDeptEntities.get(0));
				sessionUserBean.setWorkDept(cboDeptEntities.get(0));
				sessionUserBean.setOrg(cboOrgEntities.get(0));
				sessionUserBean.setWorkOrg(cboOrgEntities.get(0));
			}
			// 提交并赋值单号及提交时间
			String docNo = String.valueOf(pmCloseApplyEntity.getId());
			docNo = docNo.substring(0, 6) + docNo.substring(9);
			pmCloseApplyEntity.setValue("docno", docNo);
			pmCloseApplyEntity.setValue("submitdate", new Date());
			Map<String, Object> dataMap = pmCloseApplyEntity.convertToMap();
			StringBufferProxy mailtitle = new StringBufferProxy();
			mailtitle.appendSingle("系统于{0}自动提交项目闭环申请,单据编号{1}! ",
				DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
			pmCloseApplyService.executeSubmit((TapEntity) pmCloseApplyEntity, mailtitle.toString(), sessionUserBean);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}
	}
}

